<template>
    <el-form ref="advertForm" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm" status-icon>
        <el-form-item>
            <el-upload class="upload-demo" drag :on-change="handleImgChange" accept="image/*" :auto-upload="false"
                style="width:100%">
                <el-icon class="el-icon--upload">
                    <upload-filled />
                </el-icon>
                <div class="el-upload__text">
                    <div>拖拽到此处</div>
                    <div>或点击上传</div>
                </div>
                <template #tip>
                    <div class="el-upload__tip"></div>
                </template>
            </el-upload>
        </el-form-item>

        <el-form-item label="名称" prop="advert_title">
            <el-input v-model="ruleForm.advert_title" />
        </el-form-item>

        <el-form-item label="链接" prop="advert_href">
            <el-input v-model="ruleForm.advert_href" />
        </el-form-item>


        <el-form-item label="时间" required>
            <el-col :span="11">
                <el-form-item prop="advert_create_time">
                    <el-date-picker v-model="ruleForm.advert_create_time" type="date" label="" placeholder="开始"
                        style="width: 100%" />
                </el-form-item>
            </el-col>
            <el-col class="text-center" :span="2">
                <span class="text-gray-500"></span>
            </el-col>
        </el-form-item>

        <el-form-item label="描述" prop="advert_text">
            <el-input v-model="ruleForm.advert_text" type="textarea" />
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="addAdvert(advertForm)">发布</el-button>
            <el-button @click="resetForm(advertForm)">重置</el-button>
        </el-form-item>
    </el-form>
</template>
<script lang="ts" setup>
// 导入格式化时间插件
import moment from "moment";
// 导入消息提示框
import { ElMessage } from 'element-plus';
// 导入定义数据的方法
import { ref, reactive, onMounted } from 'vue';
// 导入表单组件对象
import type { FormInstance, FormRules } from 'element-plus';
// 导入上传文件图标
import { UploadFilled } from '@element-plus/icons-vue';
// 导入相关接口
import { advertPublishApi, advertModifyApi, advertDetailApi , advertDeleteApi} from '../../http/request';
// 导入创建路由方法
import { useRouter } from 'vue-router';
// 定义路由
const $router = useRouter();
// 定义变量
let advert_id:any = ref("");
// 获取token
let token:any = localStorage.getItem('token');
// 定义广告表单实例
const advertForm = ref<FormInstance>();
// 定义对象记录表单提交的数据
const ruleForm = reactive({
    advert_title: '',
    advert_href: '',
    advert_create_time: '',
    advert_text: '',
    file: ''
})
// 设置表单约束
const rules = reactive<FormRules>({
    // 标题
    advert_title: [
        { required: true, message: '请输入广告名称', trigger: 'blur' }
    ],
    // 链接
    advert_href: [
        {
            required: true,
            message: '请输入广告链接地址',
            trigger: 'change',
        },
    ],
    // 创建时间
    advert_create_time: [
        {
            type: 'date',
            required: true,
            message: '请选择一个时间',
            trigger: 'change',
        },
    ],
    // 描述文字
    advert_text: [
        { required: true, message: '请输入广告描述', trigger: 'blur' },
    ],
})
// 编写添加广告方法（轮播图）
const addAdvert = async (formObj: FormInstance | undefined) => {
    if (!formObj) return
    await formObj.validate(async (valid, fields) => {
        if (valid) {
            let { advert_title, advert_href, advert_create_time, advert_text, file } = ruleForm;
            let formData = new FormData();
            formData.append("token", token);
            formData.append('advert_href', advert_href);
            formData.append('advert_create_time', moment(new Date(advert_create_time)).format('YYYY-MM-DD HH:mm:ss'))
            formData.append('advert_text', advert_text);
            formData.append('photo', file);
            formData.append('advert_title', advert_title);
            formData.append("fileType", "IMAGE");
            // console.log("advert_id:",advert_id)
            // console.log("formData:",formData)
            if (advert_id.value) {
                // 修改广告
                formData.append("advert_id", advert_id.value)
                await advertDeleteApi({token,advert_id:advert_id.value}).then(
                    (data: any) => {
                        // console.log('2.0',data);
                    }
                )
                advertModifyApi(formData)
                    .then(
                        (data: any) => {
                            if (data.code == 200) {
                                // 重置表单
                                formObj.resetFields();
                                // 延迟300ms跳转页面
                                let timeout = setTimeout(() => {
                                    $router.push({ path: '/advert/list' });
                                    clearTimeout(timeout);
                                }, 300)
                                // 提示
                                ElMessage({
                                    message: data.msg,
                                    type: 'success',
                                });
                            } else {
                                // 提示
                                ElMessage({
                                    message: data.msg,
                                    type: 'warning',
                                });
                            }
                        }
                    ).catch(
                        err => {
                            console.log(err)
                        }
                    )
            } else {
                // 发布广告
                advertPublishApi(formData)
                    .then(
                        (data: any) => {
                            if (data.code == 200) {
                                // 重置表单
                                formObj.resetFields();
                                // 延迟300ms跳转页面
                                let timeout = setTimeout(() => {
                                    $router.push({ path: '/advert/list' });
                                    clearTimeout(timeout);
                                }, 300)
                                // 提示
                                ElMessage({
                                    message: data.msg,
                                    type: 'success',
                                });
                            } else {
                                // 提示
                                ElMessage({
                                    message: data.msg,
                                    type: 'warning',
                                });
                            }
                        }
                    )
                    .catch(
                        err => {
                            console.log(err)
                        }
                    )
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}
// 编写重置广告方法（轮播图）
const resetForm = (formObj: FormInstance | undefined) => {
    if (!formObj) return
    formObj.resetFields()
}
// 获取上传文件行为
const handleImgChange = (event: any) => {
    let file = event['raw'];
    // console.log("file:", file)
    if (file) {
        ruleForm.file = file
    } else {
        ElMessage("请选择图片。")
    }
}
// 获取广告详情
const DetailAdvert = (advert_id: any) => {
    // 获取广告详情
    advertDetailApi({ token, advert_id: advert_id.value })
        .then(
            (data: any) => {
                if (data.code == 200) {
                    let { advert_title, advert_href, advert_create_time, advert_text } = data.result[0];
                    ruleForm.advert_title = advert_title;
                    ruleForm.advert_href = advert_href;
                    ruleForm.advert_create_time = advert_create_time;
                    ruleForm.advert_text = advert_text;
                }
            }
        )
        .catch(
            error=>{
                console.log(error);
            }
        )
}
// 调用挂载钩子函数
onMounted(() => {
    // 初始化广告
    // console.log(advert_id)
    if ($router && $router.currentRoute.value.query) {
        advert_id.value = $router.currentRoute.value.query.advert_id
        // console.log(advert_id)
        if (advert_id.value) {
            DetailAdvert(advert_id)
        }
    }

})
</script>
<style lang="scss">
.el-upload-dragger {
    margin-bottom: 20px;
    padding-top: 0px;
    padding-bottom: 0px;

    div {
        padding: 0 !important;
        margin: 0 !important;
    }
}

.demo-ruleForm {
    ::v-deep .el-picker-panel__body {
        z-index: 100000000000;
        background-color: #ccc;
    }
}
</style>